<style></style>
<template>
  <div>
    <!-- 头部搜索区 -->
    <div style="margin-bottom: 10px;">
      <span>时间：</span>
      <el-input v-model="searchText" style="width: 240px;margin-right: 10px;" placeholder="请输入房产名称" />
      <span>状态：</span>
      <el-radio-group v-model="searchState" class="ml-4">
        <el-radio :value="2" size="large" :checked="true">全部</el-radio>
        <el-radio :value="0" size="large">启用</el-radio>
        <el-radio :value="1" size="large">禁用</el-radio>
      </el-radio-group>
      <el-button :icon="Search" type="primary" @click="btnSearch()" plain style="margin-left: 10px;">查询</el-button>
      <el-button @click="btnAdd()" type="success" plain><el-icon>
          <Plus />
        </el-icon>添加</el-button>
    </div>
    <!-- 表格数据展示区 -->
    <div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="费用编号" prop="Priceid" />
        <el-table-column label="时间" prop="Time" />
        <el-table-column label="使用性质" prop="Usetype">
          <template #default="scope">
            <el-tag :type="scope.row.Usetype ? 'primary' : 'success'">{{ scope.row.Usetype ? "买" : "租凭"
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="费用" prop="Useprice" />
        <el-table-column label="状态" prop="State">
          <template #default="scope">
            <el-tag :type="scope.row.State ? 'primary' : 'success'">{{ scope.row.State ? "禁用" : "启用"
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" :icon="Edit" type="warning" plain
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" :icon="Delete" type="danger" plain
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-config-provider :locale="locale">
      <div class="demo-pagination-block" style="margin-top: 10px;">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50, 100]" :small="small" :disabled="disabled" :background="background"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-config-provider>
  </div>


  <!-- 添加/编辑 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" :destroy-on-close="true"
    :before-close="clearForm">
    <el-form :model="formDate" :rules="rules" ref="ruleFormRef">
      <el-form-item label="时间" :label-width="formLabelWidth" prop="Time">
        <el-input v-model="formDate.Time" autocomplete="off" />
      </el-form-item>
      <el-form-item label="使用性质" :label-width="formLabelWidth" >
        <el-radio-group v-model="formDate.Usetype" class="ml-4">
          <el-radio :value="false" size="large">租凭</el-radio>
          <el-radio :value="true" size="large">买</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="费用" :label-width="formLabelWidth" prop="Useprice">
        <el-input v-model.number="formDate.Useprice" autocomplete="off" />
      </el-form-item>
      <el-form-item label="状态" :label-width="formLabelWidth">
        <el-radio-group v-model="formDate.State" class="ml-4">
          <el-radio :value="false" size="large">启用</el-radio>
          <el-radio :value="true" size="large">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="btnSave(ruleFormRef)">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, onMounted, reactive, markRaw } from 'vue'
import { Search, Delete, Edit } from '@element-plus/icons-vue'
import axios from 'axios'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { ElMessage, ElMessageBox, FormRules, FormInstance } from 'element-plus'

//存储表格数据信息
let tableData = ref([]);

//搜索信息
var searchText = ref("");

//条件查询状态
var searchState = ref(2);

//设置分页中文显示
const locale = ref(zhCn)


//页码数
const currentPage = ref(1)
//页条数
const pageSize = ref(5)
//总条数
var total = ref(0)

//控制打开/关闭模态框
const dialogFormVisible = ref(false)
//表单输入框前标题宽度
const formLabelWidth = '80px'

//弹出层标题
var dialogTitle = ref("")
//表单信息
var formDate = ref({
  "Priceid": 0,
  "Isdelete": false,
  "State": false,
  "Time": "",
  "Useprice": null,
  "Usetype": false
})


//切换页条数
const handleSizeChange = (val) => {
  bindData(currentPage.value, val, searchState.value, searchText.value)
}

//切换页数
const handleCurrentChange = (val) => {
  bindData(val, pageSize.value, searchState.value, searchText.value)
}
//组件加载完毕后执行
onMounted(() => {
  bindData(currentPage.value, pageSize.value, searchState.value, searchText.value)
})

//通过名称条件查询
function btnSearch() {
  bindData(currentPage.value, pageSize.value, searchState.value, searchText.value)
}

//编辑
const handleEdit = (index, row) => {
  dialogFormVisible.value = true;
  dialogTitle.value = "编辑车位费用信息";
  formDate.value = row;
}

//删除
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
    `确定要删除编号为【${row.Priceid}】的数据吗?`,
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      icon: markRaw(Delete)
    }
  ).then(() => {
    axios.delete("https://localhost:7090/api/ParkingPriceInfo?priceid=" + row.Priceid)
      .then((res) => {
        if (res.data) {
          ElMessage({
            type: 'success',
            message: "删除成功",
          })
          bindData(currentPage.value, pageSize.value, searchState.value, searchText.value);
        } else {
          ElMessage({
            type: 'error',
            message: "删除失败",
          })
        }
      }).catch((err) => {
        ElMessage({
          message: err,//"网络异常，请联系管理员!!!"
          type: 'error',
        })
      })

  })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '用户取消操作',
      })
    })
}

//添加按钮
function btnAdd() {
  dialogFormVisible.value = true;
  dialogTitle.value = "添加车位费用信息";
}

//保存
function btnSave(formEl) {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      axios({
        method: formDate.value.Priceid == 0 ? "POST" : "PUT",
        url: "https://localhost:7090/api/ParkingPriceInfo",
        data: formDate.value,
        headers: { "Content-Type": "application/json" }
      }).then((res) => {
        if (res.data){
          ElMessage({
            message: formDate.Priceid == 0 ? '添加' : '编辑' + '成功',
            type: 'success',
          })
          clearForm();
          bindData(currentPage.value, pageSize.value, searchState.value, searchText.value);
        } else {
          ElMessage({
            message: formDate.Priceid == 0 ? '添加' : '编辑' + '失败',
            type: 'error',
          })
        }
      }).catch((err) => {
        ElMessage({
          message: err,//"网络异常，请联系管理员!!!"
          type: 'error',
        })
      })
    } else {
      return false
    }
  })
}


//绑定表格数据
function bindData(page, limit, state, strName) {
  axios.get(`https://localhost:7090/api/ParkingPriceInfo?page=${page}&limit=${limit}&state=${state}&strTime=${strName}`)
    .then((res) => {
      console.log(res.data);
      tableData.value = res.data.data;
      total.value = res.data.total;
    })
}

//关闭模态框
function closeDialog(params) {
  clearForm();
  dialogFormVisible.value = false;
}

//转换日期时间
function convertDateTime(dateStr) {
  var datetimeObj = new Date(dateStr);

  var year = datetimeObj.getFullYear();
  var month = ("0" + (datetimeObj.getMonth() + 1)).slice(-2);
  var day = ("0" + datetimeObj.getDate()).slice(-2);
  var hours = ("0" + datetimeObj.getHours()).slice(-2);
  var minutes = ("0" + datetimeObj.getMinutes()).slice(-2);
  var seconds = ("0" + datetimeObj.getSeconds()).slice(-2);

  var formattedDate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  return formattedDate;
}

//清理表单
function clearForm() {
  dialogFormVisible.value = false;
  formDate.value = {
    "Priceid": 0,
    "Isdelete": false,
    "State": false,
    "Time": "",
    "Useprice": null,
    "Usetype": false
  }
}


//验证
const ruleFormRef = ref();

//表单验证
const rules = reactive({
  Time: [
    {
      required: true,
      message: '时间不能为空',
      trigger: 'change',
    },
    { max: 10, message: '时间的长度在1~20之间', trigger: 'blur' },
  ],
  Useprice: [
    {
      required: true,
      message: '费用不能为空',
      trigger: 'change',
    }
  ],
})
</script>